<?php
declare (strict_types = 1);

namespace app;

use app\exception\BusinessException;
use think\Model;

/**
 * 服务基础类
 */
abstract class BaseService
{
    /**
     * 模型实例
     * @var Model
     */
    protected $model;

    /**
     * 构造函数
     * @param Model $model
     */
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    /**
     * 获取单条记录
     * @param int $id
     * @return array
     * @throws BusinessException
     */
    public function find(int $id): array
    {
        $result = $this->model->find($id);
        if (!$result) {
            throw new BusinessException('数据不存在');
        }
        return $result->toArray();
    }

    /**
     * 获取列表
     * @param array $where 查询条件
     * @param array $order 排序条件
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public function list(array $where = [], array $order = [], int $page = 1, int $limit = 15): array
    {
        $query = $this->model->where($where);
        
        if (!empty($order)) {
            foreach ($order as $field => $sort) {
                $query->order($field, $sort);
            }
        }

        $total = $query->count();
        $items = $query->page($page, $limit)->select();

        return [
            'list' => $items ? $items->toArray() : [],
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 新增记录
     * @param array $data
     * @return int
     */
    public function create(array $data): int
    {
        $result = $this->model->create($data);
        return $result->id;
    }

    /**
     * 更新记录
     * @param int $id
     * @param array $data
     * @return bool
     * @throws BusinessException
     */
    public function update(int $id, array $data): bool
    {
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('数据不存在');
        }
        return $model->save($data);
    }

    /**
     * 删除记录
     * @param int $id
     * @return bool
     * @throws BusinessException
     */
    public function delete(int $id): bool
    {
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('数据不存在');
        }
        return $model->delete();
    }
} 